package com.tensquare.article.service;

import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.concurrent.TimeUnit;

/**
 * Created by WF on 2020/7/22 16:14
 */
@Service
@Transactional
public class ArticleService {
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private RedisTemplate redisTemplate;
    //1.进行审核
    public void examine(String articleId) {
        articleDao.examine(articleId);
    }
    //2.文章点赞
    public void thumbup(String articleId) {
        articleDao.thumbup(articleId);
    }
    //3.根据文章id得到文章对象
    public Article findById(String articleId){
        //3.1)从redis中得到文章
        Article article = (Article) redisTemplate.opsForValue().get("article_" + articleId);
        //3.2)如果不存在文章，就说明redis中没有，此时从数据库中取
        if(article == null){
            //3.3)从数据库中得到文章
            article = articleDao.findById(articleId).get();
            System.out.println("正在从数据库中得到文章信息。。。");
            //3.4)将文章放到redis中
            redisTemplate.opsForValue().set("article_"+articleId,article,10, TimeUnit.MINUTES);
        }
        //3.5)返回
        return article;
    }
    public void update(Article article) {
        //清空缓存
        redisTemplate.delete("article_"+article.getId());
        articleDao.save(article);
    }
    public void delete(String id) {
        //清空缓存
        redisTemplate.delete("article_"+id);
        articleDao.deleteById(id);
    }
}
